const multer = require("multer");
const multerS3 = require("multer-s3");
const { S3Client } = require("@aws-sdk/client-s3");
const path = require("path");

// AWS S3/R2 配置
const s3 = new S3Client({
  region: "auto",
  endpoint: "https://5373b2d8e3cf4d22d97d77d8855350ca.r2.cloudflarestorage.com",
  credentials: {
    accessKeyId: "e7d4bd8a15575362ea2c30e1d421b6a8",
    secretAccessKey:
      "ca57caac8a8bbbc4bb5e1c70e772358751fe9940d4246567d8cc81322d74ef35",
  },
});

// 公共 bucket 上传
const uploadPublic = multer({
  storage: multerS3({
    s3,
    bucket: "bizhi", // R2 的 bucket 名
    contentType: multerS3.AUTO_CONTENT_TYPE, // 启用自动内容类型检测
    acl: "public-read", // R2 可选
    key: (req, file, cb) => {
      const folder = req.query.folder || "uploads";
      // 正确处理中文文件名编码
      const originalname = Buffer.from(file.originalname, "latin1").toString(
        "utf8"
      );
      const ext = path.extname(originalname);
      const timestamp = Date.now();
      const newFilename = `${path.basename(
        originalname,
        ext
      )}_${timestamp}${ext}`;
      cb(null, `${folder}/${newFilename}`);
    },
    // 可选：设置缓存头
    cacheControl: "max-age=2592000",
    contentDisposition: "inline",
  }),
  limits: { fileSize: 20 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    const fileType = file.mimetype.split("/")[0];
    cb(null, fileType === "image");
  },
});

// 私有 bucket 上传（R2 也可以用同一个 bucket，acl: 'private'）
const uploadPrivate = multer({
  storage: multerS3({
    s3,
    bucket: "bizhi", // 直接使用 bucket 名，或者确保环境变量已设置
    contentType: multerS3.AUTO_CONTENT_TYPE, // 启用自动内容类型检测
    acl: "private",
    key: (req, file, cb) => {
      const folder = req.query.folder || "private-uploads";
      // 正确处理中文文件名编码
      const originalname = Buffer.from(file.originalname, "latin1").toString(
        "utf8"
      );
      const ext = path.extname(originalname);
      const timestamp = Date.now();
      const newFilename = `${path.basename(
        originalname,
        ext
      )}_${timestamp}${ext}`;
      cb(null, `${folder}/${newFilename}`);
    },
    contentDisposition: 'attachment; filename="file.jpg"',
  }),
  limits: { fileSize: 20 * 1024 * 1024 },
});

// 单文件上传中间件
const singleFileUpload = (req, res, next) => {
  uploadPublic.single("file")(req, res, next);
};
const singleFileUploadPrivate = (req, res, next) => {
  uploadPrivate.single("file")(req, res, next);
};

module.exports = {
  s3,
  singleFileUpload,
  singleFileUploadPrivate,
};
